package com.cd.music.utils;

import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * Created by yxl on 17-5-10.
 * AES加密解密
 */
public class AESUtil {
    private static final String ALGORITHM = "AES";
    // 密钥
    private static String key = "8495e441a6d6409d8e0f0fc39cd83b6e";
    // 偏移量
    private static int offset = 16;
    private static String transformation = "AES/CBC/PKCS5Padding";

    /**
     * 加密
     *
     * @param content 需要加密的字符串
     * @return 返回加密后的
     */
    public static String encrypt(String content) {
        return encrypt(content, key);
    }

    /**
     * 解密
     *
     * @param content 需要解密的字符串
     * @return 返回加密后的
     */
    public static String decrypt(String content) {
        return decrypt(content, key);
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return 返回加密后的
     */
    private static String encrypt(String content, String key) {
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            byte[] byteContent = content.getBytes("UTF-8");
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
            byte[] result = cipher.doFinal(byteContent);
            // 编码
            return Base64.getEncoder().encodeToString(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES（256）解密
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return 解密之后
     */
    private static String decrypt(String content, String key) {
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
            return new String(result, "UTF-8"); // 解密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 键
     *
     * @return 返回键
     */
    public String getKey() {
        KeyGenerator keyGenerator;
        try {
            keyGenerator = KeyGenerator.getInstance(ALGORITHM);
            SecureRandom secureRandom = new SecureRandom();
            final int KEY_SIZE = 256;
            keyGenerator.init(KEY_SIZE, secureRandom);
            SecretKey aesKey = keyGenerator.generateKey();
            return Base64.getEncoder().encodeToString(aesKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密
     *
     * @param content 要加密的值
     * @return 返回加密好的字符串
     */
    public static String encryption(String content) {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            SecretKeySpec secretKeySpec = new SecretKeySpec(base64Decoder.decodeBuffer(key), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] bytes = cipher.doFinal(content.getBytes("UTF-8"));
            StringBuilder hex = new StringBuilder();
            for (byte aByte : bytes) {
                int h = aByte & 0XFF;
                if (h < 16) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(h));
            }
            return hex.toString();
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryption(String content) {
        try {
            int length = content.length() >> 1;
            byte[] data = new byte[length];
            for (int i = 0; i < length; i++) {
                int n = i << 1;
                int height = Integer.valueOf(content.substring(n, n + 1), 16);
                int low = Integer.valueOf(content.substring(n + 1, n + 2), 16);
                data[i] = (byte) (height * 16 + low);
            }
            BASE64Decoder base64Decoder = new BASE64Decoder();
            SecretKeySpec secretKeySpec = new SecretKeySpec(base64Decoder.decodeBuffer(key), ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] bytes = cipher.doFinal(data);
            return new String(bytes, "UTF-8");
        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
